using System;
using System.Collections.Generic;
using System.Text;

namespace XiVo
{
  class Command
  {
    System.IO.Ports.SerialPort port;
    public Response response;
    public bool channelInfoNext;

    public Command()
    {
      port = new System.IO.Ports.SerialPort("COM5");
      response = new Response(port);
      port.Open();
      if (port.IsOpen == false)
        throw new Exception("Can't open port " + port.PortName);
    }

    public void Close()
    {
      port.Close();
    }

    public void powerUp()
    {
      byte[] data = new byte[] {
        0x00, 0x16, 0x16, 0x16, 0x01 };
      write(data);
    }

    public void powerDown()
    {
      byte[] data = new byte[] {
        0x01, 0x00 };
      write(data);
    }

    public void getRadioID()
    {
      byte[] data = new byte[] {
        0x31 };
      write(data);
    }

    public void setMute(byte mute)
    {
      byte[] data = new byte[] {
        0x13, mute };
      write(data);
    }

    public void changeChannel(int channel)
    {
      byte[] data = new byte[] {
        0x10, 0x02, (byte) channel, 0x00,0x00,0x01 };
      write(data);
    }

    public void getAllChannelInfo()
    {
      getNextChannelInfo(0);
    }

    public void getNextChannelInfo(int channel)
    {
       getChannelInfo(channel, true);
    }

    public void getChannelInfo(int channel)
    {
      getChannelInfo(channel, false);
    }

    public void getChannelInfo(int channel, bool next)
    {
      channelInfoNext = next;
      byte mode;
      if (next)
        mode = 9;
      else
        mode = 8;
      byte[] data = new byte[] {
        0x25, mode, (byte) channel, 0 };
      write(data);
    }

    public void getSignalData()
    {
      byte[] data = new byte[] {
        0x43 };
      write(data);
    }

    virtual public void write(byte[] data)
    {
      byte[] buffer;
      int length = data.Length + 6;
      buffer = new byte[length];
      buffer[0] = 0x5a;
      buffer[1] = 0xa5;
      buffer[2] = (byte)(data.Length / 256);
      buffer[3] = (byte)(data.Length & 0x00ff);
      System.Array.Copy(data, 0, buffer, 4, data.Length);
      buffer[length - 2] = 0xed;
      buffer[length - 1] = 0xed;
      port.Write(buffer, 0, length);
      //displayBuffer("<", buffer);
    }

    public void displayBuffer(string prefix, byte[] buffer)
    {
      if (buffer != null)
      {
        int len = buffer.Length;
        Console.Write(prefix + " ");
        for (int i = 0; i < len; ++i)
        {
          Console.Write(buffer[i].ToString("X2"));
          Console.Write(' ');
        }
        Console.WriteLine();
      }
    }
  }
}
